import permision from "@/js_sdk/wa-permission/permission.js"
const recorderManager = uni.getRecorderManager();

var isIos
// #ifdef APP-PLUS
isIos = (plus.os.name == "iOS")
// #endif

// ios
const judgeIosPermission = async (permisionID, content) => {
	const result = await permision.judgeIosPermission(permisionID)
	console.log("权限状态---", result)

	// 相册、相机权限：0-未发起过授权；2-发起过，拒绝授权；3-已授权

	//位置权限： 0-下次询问或在我共享时；4-使用app期间允许授权

	// 麦克风权限：1970168948-未发起过授权；1735552628-已授权；1684369017-发起过，拒绝授权


	// 针对相机和相册，当未发起过授权，返回1，让对应页面去调一次API触发授权框弹出
	if ((permisionID == "photoLibrary" || permisionID == "camera") && result == 0) {
		return 1
	}

	// 针对位置
	if (permisionID == "location" && (result == 0 || result == 4)) {
		return 1
	}

	// 针对麦克风，当未发起过授权，主动调一下录音，让对应页面去调一次API触发授权框弹出
	if (permisionID == "record" && result == 1970168948) {
		// 开始录音
		recorderManager.start();
		setTimeout(() => {
			recorderManager.stop();
		}, 500)
		return 197
	}

	if (result == 3 || result == 1735552628) return 1

	if (result == 2 || result == 1684369017) {
		uni.showModal({
			content,
			confirmText: "去授权",
			success: res => {
				if (res.confirm) {
					gotoAppPermissionSetting()
				}
			}
		});
		return result
	}
	return result
}

// android 
const requestAndroidPermission = async (permisionID, content) => {
	const result = await permision.requestAndroidPermission(permisionID)
	console.log("安卓权限状态---", result)

	let strStatus
	if (result == 1) {
		strStatus = "已获得授权"
		return result
	} else if (result == 0) {
		strStatus = "未获得授权"
		return result
	} else {

		// if (permisionID === "android.permission.READ_EXTERNAL_STORAGE") {
		// 	uni.chooseImage();
		// 	return
		// }

		strStatus = "被永久拒绝权限";
		uni.showModal({
			content: "权限被永久拒绝，请前往授权",
			confirmText: "去设置",
			// cancelText:"稍后设置"
			success: (res) => {
				if (res.confirm) {
					gotoAppPermissionSetting()
				}
			}
		});
		return result
	}
}

// 打开设置页面
export const gotoAppPermissionSetting = () => {
	permision.gotoAppPermissionSetting()
}

/**
 * 二次封装，统一处理ios/android
 * @param {String} permisionID 权限id
 */
export const requestPermission = async (permisionID) => {
	// #ifdef APP-PLUS
	if (isIos) {
		switch (permisionID) {
			case 'photoLibrary': // 相册权限，ios-相册权限
				return judgeIosPermission("photoLibrary", "该应用需要读取你的相册，以便继续你当前的操作")

			case 'camera': // 摄像头权限
				return judgeIosPermission("camera", "该应用需要你的相机，以便继续你当前的操作")

			case "location": // 位置权限
				return judgeIosPermission("location", "该应用需要你的地理位置，以便继续你当前的操作")

			case "microphone": // 麦克风权限
				return await judgeIosPermission("record", "该应用需要你的麦克风，以便继续你当前的操作")

			case "callphone": // 拨打电话权限
				return await judgeIosPermission("record", "该应用需要你的拨打电话，以便继续你当前的操作")
			default:
				uni.showToast({
					title: "权限key错误",
					icon: "none"
				})
				break;
		}
		return
	}

	switch (permisionID) {
		case 'photoLibrary': // 相册权限，android-外部存储(含相册)读取权限

			let PHOTOID = "android.permission.READ_EXTERNAL_STORAGE"; //安卓10用这个权限正常
			if (plus.os.version >= 13) {
				PHOTOID = "android.permission.READ_MEDIA_IMAGES"; // 安卓13用这个正常
			}
			// const PHOTOID = "android.permission.READ_EXTERNAL_STORAGE"; //安卓10用这个权限正常
			// const PHOTOID = "android.permission.READ_MEDIA_IMAGES"; //安卓13用这个正常，不知道是不是安卓13相册权限名称变了
			// const PHOTOID = "android.permission.WRITE_EXTERNAL_STORAGE"; //安卓13用这个正常，不知道是不是安卓13相册权限名称变了

			const _checkSTORAGE = await checkAndroidPermission(PHOTOID);
			if (_checkSTORAGE) {
				return await requestAndroidPermission(PHOTOID, "为了良好体验，请授权相机权限")
			} else {
				uni.showModal({
					title: "温馨提示",
					content: "该操作需要使用到你的相机/相册，便于你使用动态发布、创建语音房、聊天发送照片、修改头像。",
					cancelText: "稍后授权",
					confirmText: "去授权",
					success: async (res) => {
						if (res.confirm) {
							return await requestAndroidPermission(PHOTOID, "为了良好体验，请授权相册权限")
						}
					}
				})
			}
			break;

		case 'camera': // 摄像头权限
			const CAMERAID = "android.permission.CAMERA";
			const _checkCAMERA = await checkAndroidPermission(CAMERAID);
			if (_checkCAMERA) {
				return await requestAndroidPermission(CAMERAID, "为了良好体验，请授权相机权限")
			} else {
				uni.showModal({
					title: "温馨提示",
					content: "该操作需要使用到你的相机/相册，便于你使用动态发布、创建语音房、聊天发送照片、修改头像。",
					cancelText: "稍后授权",
					confirmText: "去授权",
					success: async (res) => {
						if (res.confirm) {
							return await requestAndroidPermission(CAMERAID, "为了良好体验，请授权相机权限")
						}
					}
				})
			}
			break;

		case "location": // 位置权限
			const LOCATIONID = "android.permission.ACCESS_FINE_LOCATION";
			const _checkLOCATION = await checkAndroidPermission(LOCATIONID);
			if (_checkLOCATION) {
				return await requestAndroidPermission(LOCATIONID, "为了良好体验，请授权位置权限")
			} else {
				uni.showModal({
					title: "温馨提示",
					content: "该操作需要使用到你的手机定位/位置信息，便于你使用附近功能、同城动态、选择位置",
					cancelText: "稍后授权",
					confirmText: "去授权",
					success: async (res) => {
						if (res.confirm) {
							return await requestAndroidPermission(LOCATIONID, "为了良好体验，请授权位置权限")
						}
					}
				})
			}
			break;

		case "microphone": // 麦克风权限
			const AUDIOID = "android.permission.RECORD_AUDIO";
			const _checkAUDIO = await checkAndroidPermission(AUDIOID);
			if (_checkAUDIO) {
				return await requestAndroidPermission(AUDIOID, "为了良好体验，请授权位置权限")
			} else {
				uni.showModal({
					title: "温馨提示",
					content: "该操作需要使用到你的麦克风权限，便于你语音/视频通话、录制语音",
					cancelText: "稍后授权",
					confirmText: "去授权",
					success: async (res) => {
						if (res.confirm) {
							return await requestAndroidPermission(AUDIOID, "为了良好体验，请授权麦克风权限")
						}
					}
				})
			}
			break;

		case "callphone": // 拨打电话
			const CALLPHONEID = "android.permission.CALL_PHONE";
			const _check_CALLPHONEID = await checkAndroidPermission(CALLPHONEID);
			if (_check_CALLPHONEID) {
				return await requestAndroidPermission(CALLPHONEID, "为了良好体验，请授权位置权限")
			} else {
				uni.showModal({
					title: "温馨提示",
					content: "该操作需要使用到你的拨打电话权限，便于你联系客服",
					cancelText: "稍后授权",
					confirmText: "去授权",
					success: async (res) => {
						if (res.confirm) {
							return await requestAndroidPermission(CALLPHONEID, "为了良好体验，请授权拨打电话权限")
						}
					}
				})
			}
			break;

		default:
			uni.showToast({
				title: "权限key错误",
				icon: "none"
			})
			break;
	}
	// #endif

	// #ifdef H5 || MP-WEIXIN
	console.log('权限 H5 MP-WEIXIN')
	return 1
	// #endif
}

export const checkAndroidPermission = (permissionID) => {
	return new Promise((resolve) => {
		// #ifdef APP-PLUS
		if (isIos) {
			resolve(true)
			return
		}
		plus.android.checkPermission(permissionID,
			granted => {
				console.log("checkPermission--", permissionID, "---", granted)
				// -1-未授权；0-已授权
				if (granted.checkResult == -1) {
					resolve(false)
					return
				}
				resolve(true)
			},
			error => {
				resolve(false)
				console.log("checkAndroidPermission error---", error.message);
			}
		);
		// #endif

		// #ifdef H5 || MP-WEIXIN
		console.log('权限 H5 MP-WEIXIN')
		resolve(true)
		// #endif
	})
}